package com.kc.web.controller.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kc.business.domain.BizShipping;
import com.kc.business.domain.KcGoodsOrderShipping;
import com.kc.business.service.IBizShippingService;
import com.kc.business.service.IKcGoodsOrderShippingService;
import com.kc.common.annotation.Log;
import com.kc.common.annotation.RepeatSubmit;
import com.kc.common.core.controller.BaseController;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.core.domain.entity.SysDictData;
import com.kc.common.core.page.TableDataInfo;
import com.kc.common.enums.BusinessType;
import com.kc.common.utils.DictUtils;
import com.kc.common.utils.KdniaoUtil;
import com.kc.system.service.ISysDictDataService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 * 物流管理
 *
 * @author zhangshuo
 * @version 1.0
 * @date 2020/10/15
 */
@Slf4j
@RestController
@RequestMapping("/business/shipping")
public class BizShippingController extends BaseController {

    @Resource
    private KdniaoUtil kdniaoUtil;

    @Resource
    IBizShippingService shippingService;

    @Resource
    IKcGoodsOrderShippingService kcGoodsOrderShippingService;

    @Resource
    private ISysDictDataService sysDictDataService;

    /**
     * 物流列表
     *
     * @param shipping
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:site:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizShipping shipping) {
        startPage();
        return getDataTable(shippingService.getList(shipping));
    }

    /**
     * 新增物流
     *
     * @param shipping
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:site:add')")
    @Log(title = "物流管理", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@Validated @RequestBody BizShipping shipping) {
        return toAjax(shippingService.add(shipping));
    }

    /**
     * 修改物流
     *
     * @param shipping
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:site:edit')")
    @Log(title = "物流管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@Validated @RequestBody BizShipping shipping) {
        return toAjax(shippingService.edit(shipping));
    }

    //@PreAuthorize("@ss.hasPermi('business:shipping:getExpCode')")
    @ApiOperation(value = "识别快递公司", notes = "识别快递公司", httpMethod = "GET")
    @GetMapping("/getExpCode")
    public AjaxResult getExpCode(@NotBlank(message = "单号不能为空") String expNo) {
        try {
            return AjaxResult.success(kdniaoUtil.getExpCode(expNo));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("单号识别失败");
        }
    }

    //@PreAuthorize("@ss.hasPermi('business:shipping:getOrderTraces')")
    @ApiOperation(value = "查看物流", notes = "查看物流", httpMethod = "GET")
    @GetMapping("/getOrderTraces")
    public AjaxResult refund(@NotNull(message = "订单id不能为空") Integer orderId) throws Exception {
        List<KcGoodsOrderShipping> shippingList = kcGoodsOrderShippingService.getList(orderId);
        Map<String, Object> ret = new HashMap<>();
        JSONArray jsonArray = new JSONArray();
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("shipping_state");
        sysDictData.setStatus("0");
        List<SysDictData> shippingState = sysDictDataService.selectDictDataList(sysDictData);
        for (KcGoodsOrderShipping shipping : shippingList) {
            JSONObject jsonObject = kdniaoUtil.getOrderTracesByJson(shipping.getExpCode(), shipping.getExpNo());
            jsonObject.put("ShipperName", shipping.getShipperName());
            Collections.reverse(jsonObject.getJSONArray("Traces"));
            for (SysDictData dictData : shippingState) {
                if (dictData.getDictValue().equals(jsonObject.getString("StateEx"))) {
                    jsonObject.put("StateName", dictData.getDictLabel());
                }
                JSONArray traces = jsonObject.getJSONArray("Traces");
                if (traces.size() > 0) {
                    jsonObject.put("Traces", traces.stream().map(trace -> {
                        JSONObject traceJsonObj = JSONObject.parseObject(trace.toString());
                        if (traceJsonObj.getString("Action").equals(dictData.getDictValue())) {
                            traceJsonObj.put("ActionName", dictData.getDictLabel());
                        }
                        return traceJsonObj;
                    }).collect(Collectors.toList()));
                }
            }
            jsonArray.add(jsonObject);
        }
        if (jsonArray.size() > 1) {
            //跳列表
            ret.put("openType", "1");
        } else {
            //跳详情
            ret.put("openType", "0");
        }
        ret.put("traces", jsonArray);

        return AjaxResult.success(ret);

    }

    @PreAuthorize("@ss.hasPermi('business:shipping:getOrderTracesInfo')")
    @ApiOperation(value = "查看物流", notes = "查看物流", httpMethod = "GET")
    @GetMapping("/getOrderTracesInfo")
    public AjaxResult getOrderTracesInfo(String expNo, String expCode) throws Exception {
        JSONObject jsonObject = kdniaoUtil.getOrderTracesByJson(expCode, expNo);
        return AjaxResult.success(jsonObject);

    }
}
